package cn.leonis.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author Tobi
 * @Date 2022-07-14 下午4:54
 * leetcode 205 同构字符串
 */
public class IsomorphicStringsSolution {

    public static void main(String[] args) {
        String s = "BBA";
        String t = "BAC";
        IsomorphicStringsSolution solution = new IsomorphicStringsSolution();
        System.out.println(solution.isIsomorphic(s, t));
    }

    /**
     * 使用哈希表和映射的方式
     * @param s
     * @param t
     * @return
     */
    public boolean isIsomorphic(String s, String t) {
        Map<Character, Character> s2t = new HashMap<>();
        Map<Character, Character> t2s = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char sc = s.charAt(i);
            char tc = t.charAt(i);
            if (s2t.containsKey(sc) && s2t.get(sc) != tc || t2s.containsKey(tc) && t2s.get(tc) != sc) {
                return false;
            }
            s2t.put(sc, tc);
            t2s.put(tc, sc);
        }
        return true;
    }
}
